// 优化的路由配置 - 支持代码分割和懒加载

import React, { Suspense, ComponentType } from 'react';
import { Spin } from 'antd';
import { 
  createLazyComponent, 
  smartPreloader, 
  useIdlePreload,
  CodeSplitRouteConfig 
} from '../utils/codeSplitting';

// 加载组件的通用Suspense包装器
const LoadingFallback: React.FC<{ message?: string }> = ({ message = '加载中...' }) => (
  <div style={{ 
    display: 'flex', 
    justifyContent: 'center', 
    alignItems: 'center', 
    height: '200px',
    flexDirection: 'column'
  }}>
    <Spin size="large" />
    <div style={{ marginTop: '16px', color: '#666' }}>{message}</div>
  </div>
);

// 创建带Suspense的懒加载组件
function createSuspenseComponent(
  LazyComponent: ComponentType<any>,
  fallbackMessage?: string
): ComponentType<any> {
  return (props: any) => (
    <Suspense fallback={<LoadingFallback message={fallbackMessage} />}>
      <LazyComponent {...props} />
    </Suspense>
  );
}

// 懒加载的页面组件
export const LazyHome = createSuspenseComponent(
  createLazyComponent(
    () => import('../pages/Home').then(module => ({ default: module.default })),
    'home-page'
  ),
  '加载首页...'
);

export const LazyTextEditor = createSuspenseComponent(
  createLazyComponent(
    () => import('../pages/TextEditor').then(module => ({ default: module.default })),
    'text-editor'
  ),
  '加载文本编辑器...'
);

export const LazyDocumentList = createSuspenseComponent(
  createLazyComponent(
    () => import('../pages/DocumentList').then(module => ({ default: module.default })),
    'document-list'
  ),
  '加载文档列表...'
);

export const LazyStoryboard = createSuspenseComponent(
  createLazyComponent(
    () => import('../pages/Storyboard').then(module => ({ default: module.default })),
    'storyboard'
  ),
  '加载分镜管理...'
);

export const LazyDataCollection = createSuspenseComponent(
  createLazyComponent(
    () => import('../pages/DataCollection').then(module => ({ default: module.default })),
    'data-collection'
  ),
  '加载数据采集...'
);

export const LazyTestPage = createSuspenseComponent(
  createLazyComponent(
    () => import('../pages/TestPage').then(module => ({ default: module.default })),
    'test-page'
  ),
  '加载测试页面...'
);

export const LazyRichTextEditorDemo = createSuspenseComponent(
  createLazyComponent(
    () => import('../pages/RichTextEditorDemo').then(module => ({ default: module.default })),
    'rich-text-demo'
  ),
  '加载富文本编辑器演示...'
);

// 代码分割路由配置
export const codeSplitRoutes: CodeSplitRouteConfig[] = [
  {
    path: '/',
    componentConfig: {
      component: () => import('../pages/Home'),
      preload: true,
      priority: 'high'
    },
    preloadStrategy: {
      onHover: false,
      onIdle: true,
      priority: 'high'
    },
    chunkName: 'home-page'
  },
  {
    path: '/text',
    componentConfig: {
      component: () => import('../pages/DocumentList'),
      preload: true,
      priority: 'high'
    },
    preloadStrategy: {
      onHover: true,
      onIdle: true,
      priority: 'high'
    },
    chunkName: 'document-list'
  },
  {
    path: '/text/editor/:id?',
    componentConfig: {
      component: () => import('../pages/TextEditor'),
      preload: true,
      priority: 'high'
    },
    preloadStrategy: {
      onHover: true,
      onIdle: true,
      priority: 'high'
    },
    chunkName: 'text-editor'
  },
  {
    path: '/storyboard',
    componentConfig: {
      component: () => import('../pages/Storyboard'),
      preload: false,
      priority: 'normal'
    },
    preloadStrategy: {
      onHover: true,
      onIdle: true,
      priority: 'normal'
    },
    chunkName: 'storyboard'
  },
  {
    path: '/data-collection',
    componentConfig: {
      component: () => import('../pages/DataCollection'),
      preload: false,
      priority: 'low'
    },
    preloadStrategy: {
      onHover: true,
      onIdle: false,
      priority: 'low'
    },
    chunkName: 'data-collection'
  },
  {
    path: '/test',
    componentConfig: {
      component: () => import('../pages/TestPage'),
      preload: false,
      priority: 'low'
    },
    preloadStrategy: {
      onHover: false,
      onIdle: false,
      priority: 'low'
    },
    chunkName: 'test-page'
  },
  {
    path: '/demo/rich-text',
    componentConfig: {
      component: () => import('../pages/RichTextEditorDemo'),
      preload: false,
      priority: 'low'
    },
    preloadStrategy: {
      onHover: false,
      onIdle: false,
      priority: 'low'
    },
    chunkName: 'rich-text-demo'
  }
];

// 预加载管理器
export class RoutePreloadManager {
  private initialized = false;

  /**
   * 初始化路由预加载
   */
  initialize(): void {
    if (this.initialized) {
      return;
    }

    console.log('[路由预加载] 开始初始化预加载策略');

    // 预加载高优先级路由
    const highPriorityRoutes = codeSplitRoutes.filter(
      route => route.componentConfig.preload && route.componentConfig.priority === 'high'
    );

    highPriorityRoutes.forEach(route => {
      smartPreloader.addPreloadTask(
        route.componentConfig.component,
        route.chunkName,
        'high'
      );
    });

    // 设置空闲时预加载
    this.setupIdlePreload();

    this.initialized = true;
    console.log('[路由预加载] 预加载策略初始化完成');
  }

  /**
   * 设置空闲时预加载
   */
  private setupIdlePreload(): void {
    const idlePreloadComponents = codeSplitRoutes
      .filter(route => route.preloadStrategy?.onIdle)
      .map(route => ({
        importFn: route.componentConfig.component,
        chunkName: route.chunkName
      }));

    // 使用空闲预加载Hook
    useIdlePreload(idlePreloadComponents, true);
  }

  /**
   * 预加载特定路由
   */
  preloadRoute(routePath: string): void {
    const route = codeSplitRoutes.find(r => r.path === routePath);
    if (route) {
      smartPreloader.addPreloadTask(
        route.componentConfig.component,
        route.chunkName,
        route.componentConfig.priority || 'normal'
      );
    }
  }

  /**
   * 获取预加载状态
   */
  getPreloadStatus(): {
    totalRoutes: number;
    preloadedRoutes: number;
    pendingRoutes: number;
  } {
    const status = smartPreloader.getQueueStatus();
    return {
      totalRoutes: codeSplitRoutes.length,
      preloadedRoutes: status.completed,
      pendingRoutes: status.pending
    };
  }
}

// 全局路由预加载管理器
export const routePreloadManager = new RoutePreloadManager();

// 初始化预加载策略
export function initializeRoutePreloading(): void {
  // 延迟初始化，确保应用已经启动
  setTimeout(() => {
    routePreloadManager.initialize();
  }, 1000);
}